package demo1;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: SEKI TOMOKI
 * Date: 2023-08-29
 * Time: 21:41
 */
class Student implements Comparable<Student>{
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }
}

//创建一个比较学生年龄的比较器
class AgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}
//创建一个比较学生名字的比较器
class NameComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}
public class Test {
    //自己实现一个排序，参数是一个接口，只有实现了Comparable接口的类才能被调用
    public static void bubbleSort(Comparable[] comparables) {
        for (int i = 0; i < comparables.length - 1; i++) {
            for (int j = 0; j < comparables.length - 1 - i; j++) {
                //调用 Student类当中的 compareTo方法进行比较
                if(comparables[j].compareTo(comparables[j + 1]) > 0) {
                    Comparable tmp = comparables[j];
                    comparables[j] = comparables[j + 1];
                    comparables[j + 1] = tmp;
                }
            }
        }
    }
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("zhangsan",30);
        students[1] = new Student("lisi",20);
        students[2] = new Student("wangwu",10);
        System.out.println(Arrays.toString(students));
        //第一种排序方式：直接在Student类中实现Comparable<Student>接口并使用
        bubbleSort(students);//只有在 类 当中实现了 Comparable接口，才能被调用
        System.out.println(Arrays.toString(students));

        //第二种排序方式：单独创建一个该类的比较器，通过比较器进行比较
        AgeComparator ageComparator = new AgeComparator();
        NameComparator nameComparator = new NameComparator();
        Arrays.sort(students,nameComparator);
        System.out.println(Arrays.toString(students));
    }
}
